package org.lzfto.flink.demo.config.web;

import java.io.IOException;

import jakarta.servlet.*;
import org.lzfto.flink.demo.system.security.service.SysUserService;
import org.lzfto.flink.demo.utils.SpringUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class CustomFilter implements Filter {
	
	
	private SysUserService userService;
	// 定义需要放行的静态资源路径前缀（根据实际目录调整）
    private static final String[] STATIC_RESOURCE_PREFIXES = {
        "/css/", 
        "/js/", 
        "/images/"
    };

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
        String uri = httpRequest.getRequestURI();
        //LOGGER.debug("访问:{}",uri);
        
        boolean isStaticResource = false;
        for (String prefix : STATIC_RESOURCE_PREFIXES) {
            if (uri.startsWith(prefix)) {
                isStaticResource = true;
                break;
            }
        }
        
        if (isStaticResource) {
            // 如果是静态资源，直接放行
            chain.doFilter(request, response);
            return;
        }
        
        if(uri.endsWith(".html") || uri.endsWith(".css") ||
        		uri.endsWith(".js")
        		) {
        	chain.doFilter(request, response);
            return;
        }
        
        if (uri.equals("/login") ||  uri.equals("/security/account/login") || uri.equals("/websocket") ) {
        	 chain.doFilter(request, response);
             return;
        }
        
        
        
        if (this.userService==null) {
        	this.userService=SpringUtils.getBean(SysUserService.class);
        }
        
        String token=httpRequest.getHeader("auth2045");
        if (token==null) {
            RequestDispatcher dispatcher = httpRequest.getRequestDispatcher("/login");
            dispatcher.forward(request, response);
            return; // 终止过滤器链
        }
        else if (!userService.isAuthenticated(token)) {
        	//LOGGER.warn("尚未登录");
            RequestDispatcher dispatcher = httpRequest.getRequestDispatcher("/login");
            dispatcher.forward(request, response);
            return; // 终止过滤器链
        }
        
        //判断是否存在合法的token.
        
		chain.doFilter(request, response);
	}

}
